import React, { Component, createRef } from 'react'
import { Form, Input, Button, Card, message, Upload, Icon } from 'antd'

import moment from 'moment'

import E from 'wangeditor'

import { postNews } from '../../../requests/index'

import './NewsPublish.less'

const { Item: FormItem } = Form

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 14 }
}

@Form.create()
export default class NewsPublish extends Component {
  constructor() {
    super()
    this.editorRef = createRef()
    this.state = {
      author: '',
      createAt: '',
      title: '',
      content: '',
      imageUrl: ''
    }
  }

  handleSubmit = () => {
    this.props.form.validateFields((err, values) => {
      const userId = JSON.parse(window.sessionStorage.getItem('usermessage'))
        .userid
      if (err) {
        return message.error('请填写必填字段')
      } else {
        postNews({ userId, data: values }).then(resp => {
          if (resp.data.res_code === 200) {
            message.success('上传成功')
            this.props.history.push('/admin/newsadmin')
          }
        })
      }
    })
  }
  initEditor = () => {
    this.editor = new E(this.editorRef.current)
    this.editor.customConfig.onchange = html => {
      // html 即变化之后的内容
      this.setState({
        content: html
      })
    }
    this.editor.create()
  }
  //发布消息
  getData = () => {
    postNews(this.props.match.params.id).then(resp => {
      if (resp.data.code === 200) {
        const { author, createAt, title, content } = resp.data.data
        this.setState(
          {
            author,
            createAt,
            title,
            content
          },
          () => {
            this.editor.txt.html(this.state.content)
          }
        )
      }
    })
  }
  //上传图片
  getBase64 = (img, callback) => {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }
  handleChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true })
      return
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false
        })
      )
    }
  }
  beforeUpload = file => {
    const isJPG = file.type === 'image/jpeg'
    if (!isJPG) {
      message.error('目前只支持 JPG 格式的图片!')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片必须小于 2MB!')
    }
    return isJPG && isLt2M
  }

  componentDidMount() {
    this.initEditor()
    this.getData()
  }

  render() {
    const { getFieldDecorator } = this.props.form
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    )
    const imageUrl = this.state.imageUrl
    return (
      <Card title={'消息发布'} bordered={false} style={{ margin: '16px' }}>
        <Form className="login-form">
          <FormItem label="消息标题" {...formItemLayout}>
            {getFieldDecorator('title', {
              rules: [
                {
                  required: true,
                  message: '请输入文章标题'
                }
              ],
              initialValue: this.state.title
            })(<Input placeholder="文章标题" />)}
          </FormItem>
          <FormItem label="消息描述" {...formItemLayout}>
            {getFieldDecorator('describe', {
              rules: [
                {
                  required: true,
                  message: '请对本消息进行简短描述'
                }
              ],
              initialValue: this.state.title
            })(<Input placeholder="文章标题" />)}
          </FormItem>
          <FormItem label="消息图片" {...formItemLayout}>
            {getFieldDecorator('picture', {
              rules: [
                {
                  required: true,
                  message: '请为本消息配上图片'
                }
              ],
              initialValue: this.state.title
            })(
              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                beforeUpload={this.beforeUpload}
                onChange={this.handleChange}
              >
                {imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}
              </Upload>
            )}
          </FormItem>
          <FormItem label="消息内容" {...formItemLayout}>
            {getFieldDecorator('content', {
              rules: [
                {
                  required: true,
                  message: '请输入消息内容'
                }
              ],
              initialValue: this.state.content
            })(<div className="editor" ref={this.editorRef} />)}
          </FormItem>
          <FormItem
            wrapperCol={{
              offset: 4
            }}
          >
            <Button type="primary" onClick={this.handleSubmit}>
              保存
            </Button>
          </FormItem>
        </Form>
      </Card>
    )
  }
}
